import { Inject, Controller, Get, Post, Body, Query, Files, Fields } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { IdleService } from '../../service/user/idle.service';
import { Idle } from '../../entity/user/idle';
import * as fs from 'fs';
import * as path from 'path';


@Controller('/api/user')
export class APIController {
  @Inject()
  ctx: Context;

  @Inject()
  idleService: IdleService;
  

  @Get('/idle', { description: '获得闲置表' })
  async getidle(@Query('ownerid') ownerid: string) {
    const result = await this.idleService.getidle(ownerid)
    if(result.length!=0){
      for(var i = 0 ;i< result.length; i++){
        const fileName = result[i].image;
        const idlepic = fs.readFileSync(path.join(__dirname, '../../../public/upload/idle', fileName));
        result[i]["src"] = idlepic  
        result[i]["type"] = "闲置"      
      } 
    }
    return { success: true, message: '闲置查询成功', data: { result } }
  }

  @Post('/idle', { description: '提交闲置' })
  async idle(@Body() idle: Idle) {
    console.log(idle);
    const result = await this.idleService.idle(idle)
    return { success: true, message: '闲置提交成功', data: { result } }
  }

  @Post('/idlepic', { description: '添加闲置图片' })
  async addpic(@Files() files, @Fields() Fields) {
    console.log("files", files);
    console.log("Fields", Fields);
    const image = files
    // 指定图片存储的路径
    const filePath = path.join(__dirname, '../../../public/upload/idle', image[0].filename);
    // 将图片数据写入到指定的文件中
    fs.writeFileSync(filePath, fs.readFileSync(image[0].data));

    const result = await this.idleService.addidlepic(image[0].filename, Fields.id)
    return { success: true, message: '添加闲置图片成功', data: { result } }
  }

 
}